from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import Departments
from user.models import Users


class DepartmentSerializers(ModelSerializer):
    boos_name = serializers.SerializerMethodField()
    created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)

    class Meta:
        model = Departments
        fields = ["id", "name", "boos_name", "boos_id", "description", "created_at", "updated_at"]
        read_only_fields = ["id"]

        extra_kwargs = {
            'description': {"required": False},
            'boos_id': {"write_only": True}
        }

    def validate_boos_id(self, item):
        user = Users.objects.filter(id=item).first()
        if not user:
            raise ValidationError(f"id为{item}的用户不存在，不能为他指定部门老大")
        return item

    def get_boos_name(self, obj):
        user = Users.objects.filter(id=obj.boos_id).first()
        return user.nickname
